import { CoverImage, CoverView } from '@tarojs/components'
import './index.scss'
import Taro, { useRouter } from '@tarojs/taro'
import { useEffect, useState } from 'react'

const list = [
    {
        pagePath: 'pages/rehab/index',
        selectedIconPath: 'static/tabbar-icons/dumbbell-sel.png',
        iconPath: 'static/tabbar-icons/dumbbell.png',
        text: '',
    },
    {
        pagePath: 'pages/record/index',
        selectedIconPath: 'static/tabbar-icons/calendar-small-sel.png',
        iconPath: 'static/tabbar-icons/calendar-small.png',
        text: '',
    },
    {
        pagePath: 'pages/home/index',
        selectedIconPath: 'static/tabbar-icons/home-sel.png',
        iconPath: 'static/tabbar-icons/home.png',
        text: '',
    },
    {
        pagePath: 'pages/guide/index',
        selectedIconPath: 'static/tabbar-icons/medicine-symbol-sel.png',
        iconPath: 'static/tabbar-icons/medicine-symbol.png',
        text: '',
    },
    {
        pagePath: 'pages/me/index',
        selectedIconPath: 'static/tabbar-icons/user-sel.png',
        iconPath: 'static/tabbar-icons/user.png',
        text: '',
    },
]

const CustomTabBar = () => {
    const router = useRouter()
    const [curTab, setCurTab] = useState(router.path)
    useEffect(() => {
        wx.onAppRoute(function (res) {
            setCurTab('/' + res.path)
        })
    }, [])

    const switchTo = (path) => {
        Taro.setStorageSync('cur-tab', path)
        Taro.switchTab({ url: '/' + path })
    }

    return (
        <CoverView className='tab-bar'>
            <CoverView className='tab-bar-border' />
            <CoverView className='tab-bar-items'>
                {list.map((item, index) => {
                    const selected = curTab === '/' + item.pagePath
                    const isHomeSelected =
                        selected && curTab === '/pages/home/index'
                    return (
                        <CoverView
                            className={
                                isHomeSelected
                                    ? 'tab-bar-item home-selected'
                                    : 'tab-bar-item'
                            }
                            key={index}
                            onClick={() => switchTo(item.pagePath)}
                        >
                            <CoverImage
                                src={`../${
                                    selected
                                        ? item.selectedIconPath
                                        : item.iconPath
                                }`}
                            />
                            <CoverView>{item.text}</CoverView>
                        </CoverView>
                    )
                })}
            </CoverView>
        </CoverView>
    )
}

CustomTabBar.options = {
    addGlobalClass: true,
}

export default CustomTabBar
